package com.example.redstarcommerce.cn.dh.user.utils;

import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @ClassName Sha256
 * @Author AndyWu
 * @Date 2024-12-04 21:52
 * @Motto 学不死就往死里学
 * @Version 1.0
 */
@Component
public class Sha256 {
    public String SHA256(String input){
        String password = "!@#"+input+")(*";
        try {
            // 获取 SHA-256 摘要器
            MessageDigest md = MessageDigest.getInstance("SHA-256");

            // 计算消息摘要
            byte[] messageDigest = md.digest(password.getBytes());

            // 将字节数组转换为十六进制字符串
            String hexString = bytesToHex(messageDigest);
            return hexString;

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param bytes 字节数组
     * @return 十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
